package com.hsmpay.qian4.service.ds.impl;

import com.hsmpay.common.util.NumberUtil;
import com.hsmpay.mobile.action.account.scanCodePay.MD5;
import com.hsmpay.mobile.action.account.scanCodePay.ScanCodePayParam;
import com.hsmpay.mobile.action.account.scanCodePay.SignUtils;
import com.hsmpay.qian4.pojo.PurchaseResult;
import com.hsmpay.qian4.service.ds.HsmPayService;
import com.hsmpay.utils.DesUtil;
import com.hsmpay.utils.JSONUtil;
import com.hsmpay.utils.WriteFile;
import com.hsmpay.utils.system.ConConfig;
import javapns.org.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service("ds_hsmPayService")
public class HsmPayServiceImpl implements HsmPayService{

    public static WriteFile wf = new WriteFile("ds_hsm");
    private static Logger log = LoggerFactory.getLogger(HsmPayServiceImpl.class);
    private static final String requestIp = "118.178.241.36";//请求方公网IP
    private static String CUSTOMERNUM = ConConfig.getAttribute("ZYX_CUSTOMER_NO");//商户号
    private static String MD5KEY = ConConfig.getAttribute("ZYX_MD5_KEY");//MD5密钥
    private static String SDK_CUSTOMERNUM = ConConfig.getAttribute("ZYX_SDK_CUSTOMER_NO");//SDK支付商户号
    private static String SDK_MD5KEY = ConConfig.getAttribute("ZYX_SDK_MD5_KEY");//SDK支付MD5密钥
    private static String reqUrl = ConConfig.getAttribute("ZYX_DS_REQURL");
    private static String urlStr = ConConfig.getAttribute("URL_OFFICIAL");

    /**
     * 获取消费二维码
     * @param scanCodePayParam
     * @return
     * @throws Exception
     */
    public PurchaseResult getQRCode(ScanCodePayParam scanCodePayParam) throws Exception {

        String notifyUrl = "http://"+urlStr+"/proOneMobile/zyxNotify.action";
        String outTradeNo = scanCodePayParam.getOutTradeNo();
        double totalFee = Double.valueOf(scanCodePayParam.getTotalFee());


        log.info("【起华-收款 请求参数】outTradeNo: "+ outTradeNo);
        log.info("【起华-收款 请求参数】totalFee: "+ totalFee);

        wf.log("【起华-收款 请求参数】outTradeNo: "+outTradeNo, "调试");
        wf.log("【起华-收款 请求参数】totalFee: "+totalFee, "调试");

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = sdf.format(date);
        String reqDate = dateStr.substring(0,8);
        String reqTime = dateStr.substring(8);

        SortedMap<String,String> map = new TreeMap<>();

        map.put("version", scanCodePayParam.getVersion());
        map.put("service",scanCodePayParam.getService());
        if(StringUtils.isNotBlank(scanCodePayParam.getSubOpenId())){
            map.put("openId", scanCodePayParam.getSubOpenId());
        }
        map.put("reqDate", reqDate);
        map.put("transAmount", String.valueOf(NumberUtil.roundF2(totalFee*100).longValue()));//金额转为分
        map.put("bgReturnUrl", notifyUrl);
        String cusId = "";
        String md5Key = "";
        if(scanCodePayParam.getService().equals("0004")){//SDK支付,费率与扫码不一样,需要更换商户号
            cusId = SDK_CUSTOMERNUM;
            md5Key = SDK_MD5KEY;
        }else {
            cusId = CUSTOMERNUM;
            md5Key = MD5KEY;
        }
        map.put("customerNo", cusId);
        map.put("externalId", outTradeNo);
        map.put("selfData", DesUtil.generate32Key());
        map.put("requestIp", requestIp);
        if(StringUtils.isNotBlank(scanCodePayParam.getBody())){
            map.put("description", scanCodePayParam.getBody());
        }
        map.put("reqTime", reqTime);
        map.put("appClient", StringUtils.isBlank(scanCodePayParam.getAppClient())?"0":scanCodePayParam.getAppClient());

        Map<String,String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() +1) * 10);
        SignUtils.buildPayParams(buf,params,false);
        String preStr = buf.toString();
        String sign = MD5.sign(preStr, "&key=" + md5Key, "utf-8");
        map.put("sign", sign);

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.putAll(map);

        JSONObject jsonObject = new JSONObject(paramMap);
        log.info("【起华-收款 请求参数】:" + jsonObject.toString());

        String responseUrl = "";

        Map<String, String> resultMap = new HashMap<>();
        if(ConConfig.isFormal()){
            wf.log("【起华-收款】请求环境:生产环境", "调试");

            CloseableHttpResponse response = null;
            CloseableHttpClient client = null;
            try {
                HttpPost httpPost = new HttpPost(reqUrl);
                StringEntity entityParams = new StringEntity(jsonObject.toString(), "utf-8");
                httpPost.setEntity(entityParams);
                httpPost.setHeader("Content-Type", "text/xml;charset=ISO-8859-1");
                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                if (response != null && response.getEntity() != null) {
                    responseUrl = EntityUtils.toString(response.getEntity());
                    log.info("【起华-收款 响应参数】:" + responseUrl);
                    JSONObject responseJson = new JSONObject(responseUrl);

                    Map<String, String> resultJsonMap = JSONUtil.parseToBean(responseJson.toString());
                    if(resultJsonMap.containsKey("payInfo") && StringUtils.isNotBlank(resultJsonMap.get("payInfo"))){
                        String payInfoString = resultJsonMap.get("payInfo");
                        JSONObject payInfo = new JSONObject(payInfoString);
                        Iterator<String> payInfoItr = payInfo.keys();
                        while (payInfoItr.hasNext()) {
                            String name = payInfoItr.next();
                            resultMap.put(name, payInfo.getString(name));
                        }
                        responseJson.remove("payInfo");
                    }
                    Iterator<String> nameItr = responseJson.keys();
                    while (nameItr.hasNext()) {
                        String name = nameItr.next();
                        resultMap.put(name, responseJson.getString(name));
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("【起华-收款】 系统异常!");
                throw e;
            }
        }

        PurchaseResult pr = new PurchaseResult();
        pr.setReqMsg("获取交易订单失败,请稍后再试!");
        pr.setStatus(0);
        pr.setReqCode("0001");

        if(resultMap.isEmpty()){
            return pr;
        }

        String code = resultMap.get("code");

        if(code.equals("0")){//通讯成功
            pr.setPayUrl(resultMap.get("payUrl"));//返回的扫码支付地址
            pr.setAppId(resultMap.get("appId"));
            pr.setTimestamp(resultMap.get("timeStamp"));
            pr.setNonceStr(resultMap.get("nonceStr"));
            pr.setPrepayId(resultMap.get("package"));
            pr.setPaySign(resultMap.get("paySign"));
            pr.setPayImg(resultMap.get("payImg"));
            pr.setTokenId(resultMap.get("tokenId"));
            pr.setReqMsg("获取交易订单成功!");
            pr.setReqCode("0000");
        }else {
            String message = resultMap.get("message");
            pr.setReqMsg(message);
        }
        return pr;
    }

}
